package com.test;


import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
 
public class NettyUdpTest02 {
 
	public static Integer SPORT = 3479;
	public static Integer DPORT = 3478;
	public static String REMOTE_HOST = "stunserver.org";
	//public static String REMOTE_HOST = "113.66.1.58";
	//public static String REMOTE_HOST = "192.168.2.85";
	
 
	public static void main(String[] args) {
 
		NioEventLoopGroup group = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
 
		bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
				.handler(new ChannelInitializer<NioDatagramChannel>() {
 
					@Override
					protected void initChannel(NioDatagramChannel ch) throws Exception {
						ch.pipeline().addLast(new MyHandlerSend2());
					}
				});
		try {
			Channel channel = bootstrap.bind(SPORT).sync().channel();
			InetSocketAddress remoteAddress = new InetSocketAddress(REMOTE_HOST, DPORT);
			int i = 1;
			for (; ; i++) {
				TimeUnit.SECONDS.sleep(3);
				String msg = "send " + i;
 
				ByteBuf byteBuf1 = new UnpooledByteBufAllocator(false).buffer();
				byteBuf1.writeCharSequence(msg, Charset.forName("utf-8"));
				DatagramPacket packet = new DatagramPacket(byteBuf1, remoteAddress);
				channel.writeAndFlush(packet);
				System.out.println(msg);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
 
class MyHandlerSend2 extends SimpleChannelInboundHandler<DatagramPacket> {
 
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
 
		ByteBuf buf = msg.content();
		String strMsg = buf.toString(CharsetUtil.UTF_8);
		System.out.println("Recv Send :" + strMsg);
	}
}